package com.dh.convert.rule.function;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;
import com.googlecode.aviator.exception.ExpressionRuntimeException;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.function.system.DateFormatCache;
import com.googlecode.aviator.runtime.type.AviatorObject;
import com.googlecode.aviator.runtime.type.AviatorString;

public class GetDateFunction extends AbstractFunction {

	@Override
	public AviatorString call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2, AviatorObject arg3) {
		String date = FunctionUtils.getStringValue(arg1, env);
		String orgFormat = FunctionUtils.getStringValue(arg2, env);
		String format = FunctionUtils.getStringValue(arg3, env);
		SimpleDateFormat orgDateFormat = DateFormatCache.getOrCreateDateFormat(orgFormat);
		SimpleDateFormat dateFormat = DateFormatCache.getOrCreateDateFormat(format);
		try {
			return new AviatorString(dateFormat.format(orgDateFormat.parse(date)));
		} catch (ParseException e) {
			throw new ExpressionRuntimeException("Cast string to date failed", e);
		}

	}

	@Override
	public String getName() {
		return "getDate";
	}

}
